// 和用户相关的状态管理
import { request } from "@/utils";
import { createSlice } from "@reduxjs/toolkit";
// 避免重名
import { getToken, setToken as _setToken, removeToken } from "@/utils";
import { loginAPI, getUserInfoAPI } from "@/apis/user";

const userStore = createSlice({
  name: "user",
  initialState: {
    // token: localStorage.getItem('token_key') || "",
    token: getToken() || "", // 从localStorage中获取token
    userInfo:{}, // 用户信息
  },
  // 同步修改方法
  reducers: {
    setToken(state, action) {
      state.token = action.payload
      // localStorage.setItem("token_key", action.payload)
      _setToken(action.payload) // 将token存储到localStorage中
    },
    setUserInfo(state, action){
      state.userInfo = action.payload
    },
    // 清除token和用户信息
    clearUserInfo(state){
      state.token = ""
      state.userInfo = {}
      removeToken()
    }
  }
})

// 解构出actionCreators
const { setToken, setUserInfo, clearUserInfo } = userStore.actions
// 获取reducer
const userReducer = userStore.reducer

// 异步方法，完成登录获取token
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    // 1. 发送异步请求，获取token
    // const res = await request.post("/authorizations", loginForm)
    const res = await loginAPI(loginForm)
    // 2. 提交同步action，修改token
    dispatch(setToken(res.data.token))
    // 3. 将token存储到localStorage中,这里res.data.token, action.payload, state.token都是token
    localStorage.setItem("token_key", res.data.token)
  }
}

// 获取个人用户信息异步方法
const fetchUserInfo = () => {
  return async (dispatch) => {
    // 1. 发送异步请求，获取用户信息
    // const res = await request.get("/user/profile")
    const res = await getUserInfoAPI()
    // 2. 提交同步action，修改用户信息
    dispatch(setUserInfo(res.data))
  }
}

// 导出
export { setToken, fetchLogin, setUserInfo, fetchUserInfo, clearUserInfo }
export default userReducer